<?php
/**
 * 题目链接 https://leetcode.cn/problems/add-binary/description/
 */

class Solution {

    /**
     * 先补齐位数 再从最后一位加
     * @param String $a
     * @param String $b
     * @return String
     */
    public static function addBinary(string $a, string $b): string 
    {
        $max = max(strlen($a), strlen($b));
        $a = sprintf("%0{$max}s", $a);
        $b = sprintf("%0{$max}s", $b);
        
        $result = '';
        $plus = 0;
        for ($i=$max - 1; $i >= 0; $i--) { 
            $last = $a[$i] + $b[$i] + $plus;
            switch ($last) {
                case 0:
                    $result = '0' . $result;
                    $plus = 0;
                    break;
                case 1:
                    $result = '1' . $result;
                    $plus = 0;
                    break;
                case 2:
                    $result = '0' . $result;
                    $plus = 1;
                    break;
                case 3:
                    $result = '1' . $result;
                    $plus = 1;
                    break;
                default:
                    # code...
                    break;
            }
            if ($i == 0 && $plus == 1) {
                $result = '1' . $result;
            }
        }

        return $result;
    }

}

$test = [
    ["11", "1"],
    ["1010", "1011"],
    ['0', '0']
];
$result = [
    "100",
    "10101",
    '0'
];

foreach ($test as $key => $value) {
    $r = Solution::addBinary($value[0], $value[1]);
    if ($r !== $result[$key]) {
        echo sprintf("第%d个case不通过", $key) . PHP_EOL;
    }
    echo $r . PHP_EOL;
}